﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BitTorrentSharp.Peers
{
	/// <summary>
	/// Represent as the handshake message between peers.
	/// </summary>
	public class HandshakeMessage : PeerMessage
	{

		// TODO: Consider to use byte[8] instead of an Int64 value.
		/// <summary>
		/// <summary>
		/// Get or set the 8 reversed bytes for the handshake message.
		/// </summary>
		public long Reversed
		{
			get;
			set;
		}

		/// <summary>
		/// Get or set the 20 bytes SHA1 hash value for the download file.
		/// </summary>
		public byte[] Sha1Hash
		{
			get;
			set;
		}

		/// <summary>
		/// Get or set the 20 bytes Peer ID of the target.
		/// </summary>
		public byte[] PeerId
		{
			get;
			set;
		}

		/// Get or set the leading message of the handshake string.
		/// </summary>
		public string LeadingMessage
		{
			get;
			set;
		}

		/// <summary>
		/// Represent as the content in the handshake message. This field is a constant.
		/// </summary>
		public const string HandshakeString = "BitTorrent protocol";

		/// <summary>
		/// The content byte sequence. This field is read-only.
		/// </summary>
		/// <remarks>
		/// Using this field in order to enhance the performace.
		/// </remarks>
		private static readonly byte[] ContentBytes = Encoding.ASCII.GetBytes(HandshakeString);

		/// <summary>
		/// Get all the bytes of this message.
		/// </summary>
		/// <returns>The byte sequence of this message.</returns>
		protected override byte[] GetBytesCore()
		{
			var reversedBytes = BitConverter.GetBytes(this.Reversed).EnsureBigEndian();

			return ByteHelper.Concat(ContentBytes, reversedBytes, this.Sha1Hash, this.PeerId);
		}
	}
}
